package util;

import model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Session工具类
 * 功能：从Session获取当前登录用户、判断用户是否登录
 */
public class SessionUtils {

    // Session中存储用户对象的key
    private static final String SESSION_USER_KEY = "user";

    /**
     * 从Session获取当前登录用户
     */
    public static User getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            return (User) session.getAttribute(SESSION_USER_KEY);
        }
        return null;
    }

    /**
     * 判断用户是否登录
     */
    public static boolean isLoggedIn(HttpServletRequest request) {
        return getCurrentUser(request) != null;
    }

    /**
     * 获取当前登录用户的ID
     */
    public static Integer getCurrentUserId(HttpServletRequest request) {
        User user = getCurrentUser(request);
        return user != null ? user.getId() : null;
    }

    /**
     * 设置当前登录用户到Session（登录Servlet）
     */
    public static void setCurrentUser(HttpServletRequest request, User user) {
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_USER_KEY, user);
        session.setMaxInactiveInterval(30 * 60); // 30分钟
    }

    /**
     * 用户注销
     */
    public static void logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
}